<template>
  <div>
    <div id="print-wrap">
      <table class="table table-bordered vertical-align-middle text-center" v-loading="loading">
        <tbody>
          <tr>
            <td>主体姓名</td>
            <td>{{ relatedData.customer_name || '' }}</td>
            <td>贷款金额（万元）</td>
            <td>
              <span>{{ contract.reply_funds }}</span>
            </td>
            <td>用款期限（年）</td>
            <td>
              <span class="px-2">{{ contract.load_years || '-' }}</span>
              年
            </td>
          </tr>
          <tr>
            <td>贷款利率</td>
            <td>
              <span class="px-2">{{ contract.load_rate || '-' }}</span>
              %
            </td>
            <td>放款时间</td>
            <td :class="isViewMode ? '' : 'input-td'">
              <span class="px-2" v-if="isViewMode">
                {{ $utils.dateFormat(contract.load_date, 'yyyy-MM-dd') }}
              </span>
              <el-date-picker
                v-else
                v-model="contract.load_date"
                class="w-100"
                placeholder="放款时间"
                type="date"
                value-format="yyyy-MM-dd"
                @change="calcEndDate"
                :clearable="true"
              ></el-date-picker>
            </td>
            <td>到期时间</td>
            <td>
              <!-- <el-date-picker v-model="contract.load_end_date"
                              class="w-100"
                              placeholder="还款结束时间"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :clearable="true">
              </el-date-picker> -->
              {{ $utils.dateFormat(contract.load_end_date, 'yyyy-MM-dd') }}
            </td>
          </tr>

          <tr>
            <td>银行名称</td>
            <td>{{ relatedData.bank_name }}</td>
            <td>还款付息方式</td>
            <td colspan="3">
              <div v-if="isViewMode" class="row">
                <div class="col d-flex align-items-center">
                  <span>{{ enumRepayType[contract.repay_method] || '-' }}</span>
                </div>
                <div class="col">
                  <el-button @click="showViewRepayList">查看还款计划</el-button>
                </div>
              </div>
              <div class="row" v-else>
                <div class="col d-flex align-items-center">
                  <el-radio-group v-model="repayType" @change="onRepayTypeChange">
                    <el-radio v-for="(value, key) in enumRepayType" :label="key" :key="key">
                      {{ value }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div class="col">
                  <el-button @click="showRepayList">生成还款计划</el-button>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="text-center" v-if="!isViewMode">
      <el-button class="btn-long" type="primary" @click="handlePass">登记</el-button>
      <el-button class="btn-long" type="danger" @click="handleDismiss">取消</el-button>
    </div>

    <el-dialog
      top="30px"
      width="567px"
      append-to-body
      title="还款计划"
      class="dialog-sm"
      :close-on-click-modal="false"
      :before-close="onRepayClose"
      :visible.sync="repayVisible"
    >
      <div v-if="repayListExist">
        <el-table :data="viewRepayList" :height="dialogMaxheight" border>
          <el-table-column label="还款时间" prop="pay_time" align="center">
            <template slot-scope="scope">
              <span>{{ $utils.dateFormat(scope.row.pay_time, 'yyyy年MM月dd日') }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="是否还本"
                         align="center">
          <template slot-scope="scope">
            <span>{{enumRepayInterest[scope.row.is_capital]}}</span>
          </template>
        </el-table-column> -->
          <el-table-column label="本金（元）" prop="capital" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.is_capital === '1' ? scope.row.capital : '-' }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="是否还息"
                         align="center">
          <template slot-scope="scope">
            <span>{{enumRepayInterest[scope.row.is_interest]}}</span>
          </template>
        </el-table-column> -->
          <el-table-column label="还息（元）" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.is_interest === '1' ? scope.row.interest : '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="row-sum">
          <div class="row-sum-td">合计</div>
          <div class="row-sum-td"></div>
          <div class="row-sum-td">
            <span class="pr-3">{{ editSums[0] }}</span>
          </div>
          <div class="row-sum-td"></div>
          <div class="row-sum-td">
            <span class="pr-3">{{ editSums[1] }}</span>
          </div>
        </div>
      </div>
      <div v-else>
        <el-table
          :data="repayList"
          :height="dialogMaxheight"
          border
          cell-class-name="input-td"
          v-loading="repayLoading"
        >
          <el-table-column label="还款时间" align="center" :width="rowWidth">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.pay_time"
                type="date"
                class="w-100 text-center"
                value-format="yyyy-MM-dd"
                format="yyyy年MM月dd日"
                :clearable="false"
                :placeholder="`选择${scope.$index === 0 ? '开始' : ''}还款时间`"
                @change="v => onSelectFirstRepayDate(v, scope.$index)"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="本金（元）" align="center" :width="rowWidth">
            <template slot-scope="scope">
              <div v-show="scope.row.is_capital === '1'">
                <div class="d-flex">
                  <el-input
                    v-model="scope.row.capital"
                    type="number"
                    class="flex-1 text-center"
                    min="0"
                    placeholder="输入本金"
                  ></el-input>
                  <div
                    class="auto-fill-icon"
                    title="自动填写到所有下面的列"
                    @click="onAutoFill(scope.row, scope.$index)"
                  >
                    <i class="fa fa-fw fa-angle-double-down"></i>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="利息（元）" prop="interest" align="center" :width="rowWidth">
            <template slot-scope="scope">
              <div
                v-show="scope.row.is_interest === '1' && isLastMonthAtQuarter(scope.row.pay_time)"
              >
                <div class="d-flex">
                  <el-input
                    v-model="scope.row.interest"
                    type="number"
                    class="flex-1 text-center"
                    min="0"
                    placeholder="输入利息"
                  ></el-input>
                  <div
                    class="auto-fill-icon"
                    title="自动填写到所有下面的列"
                    @click="onAutoFillInterest(scope.row, scope.$index)"
                  >
                    <i class="fa fa-fw fa-angle-double-down"></i>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="row-sum">
          <div class="row-sum-td">合计</div>
          <div class="row-sum-td"></div>
          <div class="row-sum-td">
            <span class="pr-3">{{ editSums[0] }}</span>
          </div>
          <div class="row-sum-td"></div>
          <div class="row-sum-td">
            <span class="pr-3">{{ editSums[1] }}</span>
          </div>
        </div>

        <div class="row pt-3" v-show="!repayListExist">
          <div class="col text-center">
            <el-button class="btn-long" @click="onRepayListDismiss">取消</el-button>
          </div>
          <div class="col text-center">
            <el-button class="btn-long" type="primary" @click="onRepayListFinsish">完成</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumRepayType } from '@/credit/plugins/enum'
// import warrantFeeRecordMixin from '@/bank/mixin/warrantFeeRecord'

export default {
  components: {},
  // mixins: [warrantFeeRecordMixin],
  props: {
    visible: Boolean,
    viewMode: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      loading: false,
      tableName: 'credit_level_review',
      tableRow: {},
      isReviewApiError: true,

      // 还款计划
      viewRepayList: [],
      viewRepayListError: true,
      repayType: '',
      enumRepayType,
      enumRepayInterest: {
        0: '否',
        1: '是',
      },
      repayList: [],
      rowWidth: '170px',
      repayVisible: false,
      repayLoading: false,
      dialogMaxheight: 500,
      contract: {},
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'entrustContract']),
    isViewMode() {
      return this.viewMode
    },
    // || +this.relatedData.approval_register_status !== 0
    isBankOrg() {
      return this.org.orgClass === 'org_bank'
    },
    relatedId() {
      return this.relatedData.customer_related_id
    },
    repayListExist() {
      return this.isViewMode
    },
    repayMonthType() {
      return +this.contract.repay_method === 1
    },
    hasContract() {
      return !!this.entrustContract.entrust_contract_id
    },
    editSums() {
      return this.getSums(this.repayList)
    },
    viewSums() {
      return this.getSums(this.viewRepayList)
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        this.$store.dispatch('getEntrustContract', this.relatedId)
      },
      deep: true,
      immediate: true,
    },
    entrustContract: {
      handler: function () {
        this.initContractByExist()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    calcEndDate() {
      if (this.contract.load_years.length > 2) {
        this.contract.load_years = '99'
      }

      if (this.contract.load_years && this.contract.load_date) {
        const date = new Date(this.contract.load_date)

        const year = date.getFullYear() + Number.parseInt(this.contract.load_years)
        const month = date.getMonth() + 1
        const day = Math.min(date.getDate(), new Date(year, month, 0).getDate())

        this.contract.load_end_date = `${year}-${this.panStart(month)}-${this.panStart(day)}`
      }
    },

    panStart(str) {
      return `${str || ''}`.padStart(2, '0')
    },
    initContractByExist() {
      if (!this.hasContract) {
        this.isReviewApiError = true
        return
      }
      this.isReviewApiError = false
      this.contract = { ...this.entrustContract }
      this.repayType = this.contract.repay_method
    },
    // async getData() {
    //   this.getWarrantFeeRecord(this.relatedId)
    // },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleDismiss() {
      this.$emit('dismiss', this.repayVisible)
    },
    handlePass() {
      if (this.isReviewApiError) {
        return this.$message.error('获取登记信息失败，请刷新重试！')
      }

      if (this.isBankOrg) {
        if (!this.validatorBank()) {
          return
        }
      } else {
        if (!this.validatorCredit()) {
          return
        }
      }

      this.onSave()
      // this.saveWarrantFeeRecord(this.relatedId)
    },
    validatorBank() {
      const enumValid = {
        repay_method: '请选择还款付息方式',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },
    validatorCredit() {
      const enumValid = {
        // load_date: '请输入贷款时间'
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },

    getSums(list) {
      let [capitalSum, interestSum] = [0, 0]
      for (const item of list) {
        if (item.is_capital === '1') {
          const capital = Number.parseFloat(item.capital)
          capitalSum += isNaN(capital) ? 0 : capital
        }
        if (item.is_interest === '1') {
          const interest = Number.parseFloat(item.interest)
          interestSum += isNaN(interest) ? 0 : interest
        }
      }
      return [Math.round(capitalSum * 1e2) / 1e2, Math.round(interestSum * 1e2) / 1e2]
    },

    onSave() {
      this.$utils
        .msgbox({
          message: `确定登记?`,
          type: 'info',
          beforeClose: () =>
            this.$store.dispatch('updateEntrustContract', {
              id: this.contract.entrust_contract_id,
              data: {
                repay_method: this.contract.repay_method,
                load_date: this.contract.load_date,
                load_end_date: this.contract.load_end_date,
              },
            }),
        })
        .then(() => {
          this.$message.success('登记成功！')
          this.$emit('success', true)

          this.addRepayList()
          this.$emit('success', false)
          this.beforeClose()
        })
        .catch(() => this.$message.error(`登记失败，请重试！`))
    },

    // 还款计划
    initDialogMaxHeight() {
      const clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight
      this.dialogMaxheight = clientHeight - 300
    },
    showViewRepayList() {
      this.repayVisible = true
      if (!this.viewRepayList.length) {
        this.getRepayList()
      }
    },
    async getRepayList() {
      this.repayLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData(
          this.$serviceName,
          'datum_repay_list',
          {
            'customer_related_id.eq': this.relatedId,
          },
          { pay_time: 'asc' }
        )
      )
      this.repayLoading = false
      this.viewRepayList = (res && res.data) || []
      this.viewRepayListError = Boolean(err)

      if (this.viewRepayList.length) {
        this.repayList = this.viewRepayList.map(item => ({
          pay_time: item.pay_time,
          is_interest: item.is_interest,
          interest: item.interest,
          is_capital: item.is_capital,
          capital: item.capital,
        }))
      } else {
        this.initRepayList()
      }
    },
    async addRepayList() {
      if (this.repayListExist) {
        return
      }
      const repayListData = []
      for (const item of this.repayList) {
        if (item.pay_time) {
          repayListData.push({
            customer_related_id: this.relatedId,
            pay_time: item.pay_time,
            is_interest: item.is_interest,
            interest: item.is_interest === '1' ? item.interest : '',
            is_capital: item.is_capital,
            capital: item.is_capital === '1' ? item.capital : '',
          })
        }
      }
      if (!repayListData.length) {
        return
      }

      if (this.viewRepayList.length) {
        const [, errDelete] = await this.$utils.promise(
          this.$api.deleteDataBody(this.$serviceName, 'datum_repay_list', {
            customer_related_id: this.relatedId,
          })
        )

        if (errDelete) {
          return this.$message.error('生成还款计划失败，请重试')
        }
      }

      const [, err] = await this.$utils.promise(
        this.$api.updateBatch(this.$serviceName, 'datum_repay_list', repayListData)
      )

      if (err) {
        return this.$message.error('生成还款计划失败，请重试')
      }
      this.$emit('success', false)
      this.beforeClose()
      this.getRepayList()
    },
    showRepayList() {
      if (this.repayList.length > 1) {
        // 之前修改的
        this.repayVisible = true
        return
      }
      if (!this.contract.repay_method) {
        return this.$message.warning('请先选择还款设置')
      }
      // 不是按照贷款日期来计划开始时间
      // const startDate = this.repayStart ? new Date(this.repayStart) : ''
      // if (!startDate) {
      //   return this.$message.warning('请先填写贷款日期')
      // }
      const period = +this.contract.load_years || 0
      if (!period) {
        return this.$message.warning('没有用款期限')
      }
      if (!this.viewRepayList.length) {
        this.getRepayList()
      }
      this.repayVisible = true
    },
    onSelectFirstRepayDate(val, index) {
      if (!val || index > 0) {
        return
      }
      this.repayList = [{ ...this.repayList[0] }]
      const startDate = new Date(val)
      const startYear = startDate.getFullYear()
      const startMonth = startDate.getMonth() + 1
      const startDay = startDate.getDate()
      const period = +this.contract.load_years || 0
      for (let i = 1; i < period * 12; i++) {
        let tempMonth = (startMonth + i) % 12
        if (tempMonth === 0) {
          tempMonth = 12
        }
        const tempYear =
          startYear + (Math.floor((startMonth + i) / 12) - (tempMonth === 12 ? 1 : 0))
        this.repayList.push({
          pay_time: `${tempYear}-${this.autoFillZero(tempMonth)}-${this.autoFillZero(startDay)}`,
          capital: '',
          is_interest: this.repayMonthType ? '1' : tempMonth % 3 === 0 ? '1' : '0',
          interest: '',
          is_capital: '1',
          canChange: this.repayMonthType ? true : tempMonth % 3 === 0,
        })
      }
    },
    onRepayClose() {
      this.repayVisible = false
    },
    onRepayTypeChange(val) {
      if (this.repayList.length < 2) {
        this.contract.repay_method = val
        return
      }
      this.repayType = this.contract.repay_method
      this.$confirm('已经有还款计划，更换还款设置后需要重新生成，确定修改？', '提示', {
        confirmButtonText: '确定修改',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.initRepayList()
          this.repayType = val
          this.contract.repay_method = val
        })
        .catch(() => {})
    },
    autoFillZero(num) {
      return num > 9 ? num : `0${num}`
    },
    initRepayList() {
      this.repayList = [
        {
          pay_time: '',
          interest: '',
          capital: '',
          is_interest: '1',
          is_capital: '1',
        },
      ]
    },
    onRepayListDismiss() {
      if (this.repayList.length < 2) {
        this.onRepayClose()
      } else {
        this.$confirm('确定取消还款计划，并重置填写的数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.initRepayList()
            this.onRepayClose()
          })
          .catch(() => {})
      }
    },
    onRepayListFinsish() {
      this.repayVisible = false
    },
    onAutoFill(row, index) {
      for (let i = index; i < this.repayList.length; i++) {
        this.repayList[i].capital = row.capital
      }
    },
    onAutoFillInterest(row, index) {
      for (let i = index; i < this.repayList.length; i++) {
        this.repayList[i].interest = row.interest
      }
    },
    isLastMonthAtQuarter(payTime) {
      if (this.repayMonthType || !payTime) {
        return true
      }
      return (new Date(payTime).getMonth() + 1) % 3 === 0
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.bg-gray {
  background-color: $gray-200;
}
.report-input-td {
  background-color: #ffe;
}
.auto-fill-icon {
  background-color: #ffe;
  color: $gray-500;
  line-height: 36px;
  overflow: hidden;
  cursor: pointer;
}
.text-center /deep/ .el-input__inner {
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
.label-td {
  background-color: #f8f9fa;
}
.input-td-btn {
  border-radius: 0;
  border: none;
  margin-right: 1px;
}
.row-sum {
  background-color: $gray-100;
  padding-right: 20px;
  display: flex;
  flex-wrap: nowrap;
  .row-sum-td {
    flex: 1;
    padding: 0.5rem 0.25rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }
}
</style>
